package com.quanyan.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Kingson.chan on 2016/7/8 0025.
 */


public abstract class UserCookieFilter implements Filter {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UserCookieFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, ServletResponse response)
            throws IOException {
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try{
            String uMsg = request.getHeader(Constants.USER_INFORMATION_MARK);
            Integer userId = 0 ;
            userId = getUserIdByToken(uMsg);
            if(userId != null){
                request.setAttribute("uid", userId);
            }
            else {
                request.setAttribute("uid", 0);
            }
            logger.info("================= userCookiesName:{} ==> uid:{} =================", uMsg,userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        chain.doFilter(request, response);

    }

    protected abstract Integer getUserIdByToken(String uMsg);

    @Override
    public void destroy() {

    }
}
